#!/usr/bin/env python3
import os
import subprocess
import sys
import requests
import datetime
import re

# 环境变量配置
COMMENT_BODY = os.getenv("COMMENT_BODY", "")
PRIVATE_KEY = os.getenv("private_key", "bz5pjNJpN2P95FRMDMy4zvyD")
PR_ID = os.getenv("PR_IID") or 17
BUILD_ID = os.getenv("BUILD_ID")
CI_URL = f"https://delphine-enforcive-hedgingly.ngrok-free.dev/job/KotlinNative-CI/{BUILD_ID}"


def run_cmd(cmd, cmd_path=None):
    if cmd_path is None:
        cmd_path = os.getcwd()
    print(f"执行命令: {cmd}")
    process = subprocess.Popen(
        cmd,
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        cwd=cmd_path,
        universal_newlines=True,
    )
    output_lines = []
    while True:
        line = process.stdout.readline()
        if not line and process.poll() is not None:
            break
        clean_line = re.sub(r"\x1b\[.*?m", "", line.rstrip())
        print(clean_line)
        output_lines.append(clean_line)
    return process.poll(), "\n".join(output_lines)


def send_comment(comment_data):
    headers = {"content-type": "application/json;charset=UTF-8"}
    url = f"https://api.gitcode.com/api/v5/repos/kaitianlu/kotlin_2.0/pulls/{PR_ID}/comments/?access_token={PRIVATE_KEY}&body={comment_data}"
    try:
        response = requests.request("POST", url, headers=headers)
        if response.status_code in (200, 201):
            print("✅ 评论发送成功")
            return True
        else:
            print(f"❌ 评论发送失败: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ 发送评论异常: {str(e)}")
        return False


def gradle_build():
    print("=== Gradle 构建 ===")
    if os.path.exists("gradlew"):
        run_cmd("chmod +x gradlew")
    else:
        print("❌ 未找到 gradlew")
        return False
    # run_cmd("./gradlew --stop")
    ret_code, _ = run_cmd("./gradlew :kotlin-native:dist --info")
    return ret_code == 0


def main():
    print("🚀 启动 Kotlin Native CI")
    original_dir = os.getcwd()

    # 发送开始通知
    # start_message = f"CI 任务开始"
    # send_comment(start_message)

    try:
        build_success = gradle_build()
        summary = (
            "Result: SUCCESS \n Detail:{0}".format(CI_URL)
            if build_success
            else "Result: FAILED \n Detail:{0}".format(CI_URL)
        )
        send_comment(summary)
        return build_success
    finally:
        os.chdir(original_dir)


if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)

